﻿using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Smart_Archives_Api.DTO;

namespace Smart_Archives_Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public UploadController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
        [HttpPost]
        public Response<dynamic> Post([FromForm] IFormCollection formCollection)
        {
            var resp=new Response<dynamic>();
            string result = "";
            string webRootPath = _hostingEnvironment.WebRootPath;
            string contentRootPath = _hostingEnvironment.ContentRootPath;

            FormFileCollection fileList = (FormFileCollection)formCollection.Files;
            var list = new List<string>();
            foreach (IFormFile file in fileList)
            {
                var tPath = @"/attach/" + DateTime.Now.ToString("yyyy-MM-dd") + @"/";
                string name = file.FileName;
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string filePath = webRootPath + tPath;

                string type = System.IO.Path.GetExtension(name);
                DirectoryInfo di = new DirectoryInfo(filePath);


                if (!di.Exists) { di.Create(); }

                using (FileStream fs = System.IO.File.Create(filePath + fileName + type))
                {
                    // 复制文件
                    file.CopyTo(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                }
                list.Add(tPath+fileName+type);
                result = "1";
            }
            resp.Code = 200;
            resp.Msg = "ok";
            resp.Data = list;
            return resp;
        }
    }

}